//
//  CachedImage.m
//  DialectShare
//
//  Created by timmy zhong on 3/20/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "CachedImage.h"
#import "PathHelper.h"

@interface CachedImage ()
@property (nonatomic, retain) UIButton *imageView;
- (NSString *)pathForUrl:(NSString *)url;
@end

@implementation CachedImage
@synthesize url = _url, imageView = _imageView;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.imageView = [UIButton buttonWithType:UIButtonTypeCustom];
        self.imageView.frame = self.bounds;
        [self addSubview:_imageView];

    }
    return self;
}

- (id)initWithFrame:(CGRect)frame target:(id)target selector:(SEL)sel
{
    self = [self initWithFrame:frame];
    [self.imageView addTarget:target action:sel forControlEvents:UIControlEventTouchUpInside];
    
    return self;
}

- (void)dealloc
{
    self.url = nil;
    [_imageView release];
    [super dealloc];
}

- (void)showImageForUrl:(NSString *)url defaultImage:(NSString *)aPath
{
    self.url = url;
    NSString *path = [self pathForUrl:url];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        UIImage *img = [UIImage imageWithContentsOfFile:path];
        [self.imageView setImage:img forState:UIControlStateNormal];
    } else {
        
        UIImage *img = [UIImage imageWithContentsOfFile:aPath];
        [self.imageView setImage:img forState:UIControlStateNormal];
        
        NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]] delegate:self];
        [connection start];
        [connection release];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [_imageData release];
    _imageData = [[NSMutableData alloc] initWithCapacity:128];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_imageData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    UIImage *image = [UIImage imageWithData:_imageData];
    [self.imageView setImage:image forState:UIControlStateNormal];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = [self pathForUrl:self.url];
    if ([fileManager fileExistsAtPath:path]) {
        [fileManager removeItemAtPath:path error:nil];
    }
    [_imageData writeToFile:[self pathForUrl:self.url] atomically:YES];
    [_imageData release];
    _imageData = nil;
}

- (NSString *)pathForUrl:(NSString *)url
{
    NSString *name = [PathHelper fileNameForUrl:url];
    NSString *path = [[PathHelper cacheDir] stringByAppendingPathComponent:name];
    return path;
}





@end
